# 用户登录界面
from PyQt5 import QtWidgets,QtGui
from mysql import select_sql,insert_sql,updata_sql
# from main import Start
import uuid,datetime

class User_UI(QtWidgets.QMainWindow):
    def __init__(self):
        super(User_UI, self).__init__()
        # 获取mac地址
        self.mac = uuid.UUID(int=uuid.getnode()).hex[-12:]
        # 获取当前日期
        self.today = datetime.datetime.now().strftime('%Y-%m-%d')
        self.times = 3
        self.times2 = 3
        self.clean_times_1()

    def setupUI(self):
        self.setWindowTitle("用户登录")
        self.setGeometry(100,100,300,300)
        self.Qlable1()
        self.Qlable2()
        self.QlineEdit1()
        self.QlineEdit2()
        self.QPushButton1()
        self.QPushButton2()

    def Qlable1(self):
        qlable = QtWidgets.QLabel(self)
        qlable.setText("卡号:")
        qlable.setGeometry(30,50,50,50)

    def QlineEdit1(self):
        self.lineEdit1 = QtWidgets.QLineEdit(self)
        # 限制长度
        # 限制长度16位目前不可用，只到10位
        self.lineEdit1.setMaxLength(16)
        # 只能输入数字
        self.lineEdit1.setValidator(QtGui.QIntValidator(self))
        self.lineEdit1.setGeometry(80,50,200,50)

    def Qlable2(self):
        qlable = QtWidgets.QLabel(self)
        qlable.setText("密码:")
        qlable.setGeometry(30,100,50,50)

    def QlineEdit2(self):
        self.lineEdit2 = QtWidgets.QLineEdit(self)
        # 限制长度
        self.lineEdit2.setMaxLength(6)
        # 只能输入数字
        self.lineEdit2.setValidator(QtGui.QIntValidator(self))
        self.lineEdit2.setGeometry(80,100,200,50)
        # 设置密码格式
        self.lineEdit2.setEchoMode(QtWidgets.QLineEdit.Password)

    def QPushButton1(self):
        pushbutton = QtWidgets.QPushButton(self)
        pushbutton.setText("登录")
        pushbutton.setGeometry(50,150,100,30)
        pushbutton.clicked.connect(self.QPushButton1_click)

    def QPushButton2(self):
        pushbutton = QtWidgets.QPushButton(self)
        pushbutton.setText("退回")
        pushbutton.setGeometry(150,150,100,30)
        pushbutton.clicked.connect(self.QPushButton2_click)

    def QPushButton1_click(self):
        self.lineEdit1.setText("1234567890")
        self.lineEdit2.setText("123456")
        card = self.lineEdit1.text()
        password = self.lineEdit2.text()
        # 须完成3次卡号错误当日禁止登录和3次密码错误记录卡号信息，连续3次错误修改卡的状态
        # 验证当日登录次数
        ctime = self.clean_today_time()
        if ctime == 0 :
            self.msg = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning,"警告","当日登录次数超过上限")
            return self.msg.show()
        else:
            # 验证长度开始
            result = self.clean_lineEdit(card,password)
            if result == 0 :
                self.msg = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning,"警告","卡号小于10位或者密码小于6位")
                return self.msg.show()
            # 验证结束
            else:
                # 验证卡号是否正确，不正确当日登录次数-1
                result = self.clean_card(card)
                if result == 0 :
                    # 更新当日登录的错误次数
                    self.clean_times()
                    self.msg = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, "警告", "卡号错误,剩余次数"+str(self.times))
                    return self.msg.show()
                # 验证结束
                else:
                    result = self.clean_password(card,password)
                    # 验证密码，不正确当日次数-1，3次错误需要修改卡的状态
                    if result == None :
                        # 对于密码不正确的内容进行数据库更新
                        self.clean_card_times(card)
                        self.msg = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, "警告",
                                                         "密码错误,剩余次数" + str(self.times))
                        return self.msg.show()
                    # 验证结束
                    else:
                        # 验证卡的状态
                        result = self.clean_status(card)
                        if result == 0 :
                            self.msg = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, "警告",
                                                             "此卡已被锁死，请联系管理员解锁")
                            return self.msg.show()
                        # 验证结束
                        else:
                            # 登录下一窗口
                            # 初始化卡号
                            import temp
                            from user_main import user_main
                            temp.card = card
                            # # 初始化用户界面
                            self.user_main = user_main()
                            self.user_main.setupUI()
                            self.user_main.show()
                            self.close()





    # 验证当日是否登录超过上限
    def clean_today_time(self):
        sql = "SELECT * FROM ATM.dateinfo where mac = '{0}' and  cdate = '{1}'".format(self.mac,self.today)
        result = select_sql(sql)
        times = result['times']
        # 返回次数
        return times

    # 根据密码错误的次数对卡进行锁定，3次卡密码错误记录数据库
    def clean_card_times(self,card):
        # 卡密码错误，首先更新当日错误次数
        self.clean_times()
        # 然后更新卡密码错误次数,如果次数为0，则在数据库创建
        self.times2 = self.times2 - 1
        if self.times2 == 0:
            sql = "INSERT INTO ATM.card(card,cdate) VALUES ('{0}','{1}')".format(card, self.today)
            insert_sql(sql)
            self.clean_card_date(card)

    # 已经将卡的错误记录，判断是否连续三天，连续3天锁卡
    def clean_card_date(self,card):
        yestday = (datetime.datetime.now()+datetime.timedelta(days=-1)).strftime('%Y-%m-%d')
        yestday2 = (datetime.datetime.now()+datetime.timedelta(days=-2)).strftime('%Y-%m-%d')
        sql = "SELECT * FROM ATM.card where card = '{0}'".format(card,yestday)
        result = select_sql(sql)
        sql = "SELECT * FROM ATM.card where card = '{0}'".format(card,yestday2)
        result2 = select_sql(sql)
        if result != None or result2 != None:
            sql = "UPDATE ATM.User SET status = 0 WHERE card = '{0}'".format(card)
            updata_sql(sql)


    # 根据本机的MAC地址和日期，对当日登录的错误次数进行记录
    # 首先先创建一个全新未报错的次数
    def clean_times_1(self):
        sql = "SELECT * FROM ATM.dateinfo where mac = '{0}' and cdate = '{1}'".format(self.mac, self.today)
        result = select_sql(sql)
        if result == None:
            sql = "INSERT INTO ATM.dateinfo(mac,cdate,times) VALUES ('{0}','{1}',2)".format(self.mac, self.today)
            insert_sql(sql)
        return 1

    # 然后根据错误次数进行更新
    def clean_times(self):
        self.times = self.times - 1
        sql = "UPDATE ATM.dateinfo SET times = '{0}' WHERE mac = '{1}' and cdate = '{2}'".format(self.times,self.mac,self.today)
        updata_sql(sql)

    # 验证长度是否符合要求
    def clean_lineEdit(self,card,password):
        if len(card) < 10 or len(password) < 6 :
            msg = 0
            return msg
        msg = 1
        return msg

    # 验证卡号
    def clean_card(self,card):
        sql = "SELECT * FROM ATM.User where card = '{0}'".format(card)
        result = select_sql(sql)
        if result == None:
            return 0
        else:
            return 1

    # 验证密码
    def clean_password(self,card,password):
        sql = "SELECT card = '{0}' FROM ATM.User where password = '{1}'".format(card,password)
        result = select_sql(sql)
        return result

    # 验证卡的状态
    def clean_status(self,card):
        sql = "SELECT * FROM ATM.User where card = '{0}'".format(card)
        result = select_sql(sql)
        status = result['status']
        return status

    def QPushButton2_click(self):
        # 退出后，回到主窗口
        self.close()
        from main import Start
        self.start = Start()
        self.start.setupUI()
        self.start.show()
